// import React from "react";
// import type { NextPage } from 'next';
// import { Button } from 'antd';
// import Router from 'next/router';
// import Image from 'next/image';
// import styles from '../styles/Login.module.css'
// import logo from '../assets/logo.svg';


// const login: NextPage = () => {
//   return (
//     <div className={styles.login_wrapper}>
//       {/* <Button type="primary" onClick={() => Router.push('/')}>登录</Button>
//       <Image 
//         src="https://assets.gitee.com/assets/mini_app-e5eee5a21c552b69ae6bf2cf87406b59.jpg"
//         alt="Picture of the author"
//         width={100}
//         height={100}
//       /> */}
//       <div className={styles.login_container}>
//         <div className={styles.login_body}>
//           <div className={styles.login_body_sidebox}>
//             {/* <Image 
//               src={logo}
//               alt="Picture of the author"
//               width={100}
//               height={100}
//             /> */}
//           </div>
//           <div className={styles.login_form}>
//             222222
//           </div>
//         </div>
//         <footer>
//           Gitee.com
//         </footer>
//       </div>
//     </div>
//   )
// }

// export default login;
import React, { useState } from 'react'
import useUser from '../lib/useUser'
// import Layout from '../components/layout'
import Form from '../components/form'
import fetchJson, { FetchError } from '../lib/fetchJson'

export default function Login() {
  // here we just check if user is already logged in and redirect to profile
  const { mutateUser } = useUser({
    redirectTo: '/profile-sg',
    redirectIfFound: true,
  })

  const [errorMsg, setErrorMsg] = useState('')

  return (
    <div>
      <div className="login">
        <Form
          errorMessage={errorMsg}
          onSubmit={async function handleSubmit(event) {
            event.preventDefault()

            const body = {
              username: event.currentTarget.username.value,
            }

            try {
              mutateUser(
                await fetchJson('/api/login', {
                  method: 'POST',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify(body),
                })
              )
            } catch (error) {
              if (error instanceof FetchError) {
                setErrorMsg(error.data.message)
              } else {
                console.error('An unexpected error happened:', error)
              }
            }
          }}
        />
      </div>
      <style jsx>{`
        .login {
          max-width: 21rem;
          margin: 0 auto;
          padding: 1rem;
          border: 1px solid #ccc;
          border-radius: 4px;
        }
      `}</style>
    </div>
  )
}
